package com.yunsc.shop.controller.user;

import com.yunsc.common.utils.Result;
import com.yunsc.common.utils.SecurityUtil;
import com.yunsc.common.validator.ValidationGroups;
import com.yunsc.shop.utils.ClientInfoUtils;
import com.yunsc.store.dto.CartParamsDTO;
import com.yunsc.store.service.YunscCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @version: 1.0
 * @Author: adan
 * @description: 购物车接口
 * @date: 2024-01-27 20:45
 */
@Api(tags = "购物车接口管理")
@RestController
@RequestMapping("cart")
public class CartController {

    @Resource
    private YunscCartService cartService;
    @Resource
    private ClientInfoUtils clientInfoUtils;

    @ApiOperation("查询购物车总数")
    @GetMapping("total")
    public Result<?> queryCartTotal() {
        Integer userId = SecurityUtil.getCurrentUserId();
        int count = cartService.queryUserCartCount(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("cartTotal", count);
        return Result.ok(map);
    }

    @ApiOperation("查询用户购物车")
    @GetMapping("/list")
    public Result<?> queryUserCart() {
        Integer userId = SecurityUtil.getCurrentUserId();
        if (userId == null) {
            return Result.error(401, "没有找到用户信息");
        }
        Map<String, Object> list = cartService.queryUserCart(userId);
        return Result.ok(list);
    }
    @ApiOperation("添加购物车")
    @PostMapping("/add")
    public Result<?> addCart(@RequestBody @Validated({ValidationGroups.Insert.class}) CartParamsDTO param) {
        Integer userId = SecurityUtil.getCurrentUserId();
        if (userId == null) {
            return Result.error(401, "没有找到用户信息");
        }
        Integer currentStoreId = clientInfoUtils.getCurrentStoreId();
        cartService.addCart(userId, param, currentStoreId);
        return Result.ok();
    }
    /**
     * 修改购物车
     * /cart/update
     * @param param
     * @return
     */
    @ApiOperation("修改购物车")
    @PostMapping("/update")
    public Result<?> updateCart(@RequestBody @Validated({ValidationGroups.Update.class}) CartParamsDTO param) {
        Integer userId = SecurityUtil.getCurrentUserIdEx();
        Integer cartTotal = cartService.updateCartById(userId, param);
        Map<String, Object> map = new HashMap<>();
        map.put("cartTotal", cartTotal);
        return Result.ok(map);
    }
    @ApiOperation("清空购物车")
    @PostMapping("/clear")
    public Result<?> clearCart(@RequestBody @Validated({ValidationGroups.Delete.class}) CartParamsDTO param) {
        Integer userId = SecurityUtil.getCurrentUserIdEx();
        Integer cartTotal = cartService.clearUserCart(userId, param.getCartIds());
        Map<String, Object> map = new HashMap<>();
        map.put("cartTotal", cartTotal);
        return Result.ok(map);
    }


}
